package com.zjuh.goodboy.index.lucene;

import java.util.HashMap;
import java.util.Map;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Fieldable;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.Field.TermVector;

import com.zjuh.goodboy.items.Item;
import com.zjuh.sweet.lang.StringUtil;

public class LuceneDocUtil {
	
	public static Document toDocument(Item item) {
		Document doc = new Document();
		addField(doc, "id", String.valueOf(item.getId()), Store.YES, Index.NOT_ANALYZED, TermVector.NO);
		addField(doc, "name", item.getName(), Store.YES, Index.ANALYZED, TermVector.WITH_POSITIONS_OFFSETS);
		addField(doc, "url", item.getUrl(), Store.YES, Index.NO, TermVector.NO);
		addField(doc, "imgUrl", item.getImgUrl(), Store.YES, Index.NO, TermVector.NO);
		addField(doc, "siteName", item.getSiteName(), Store.YES, Index.NOT_ANALYZED, TermVector.NO);
		addField(doc, "description", item.getDescription(), Store.YES, Index.NO, TermVector.NO);
		return doc;
	}
	
	public static Field addField(Document doc, String name, String value, Store store, Index index, TermVector termVector) {
		if (StringUtil.isEmpty(name) || StringUtil.isEmpty(value)) {
			return null;
		}
		Field field = new Field(name, value, store, index, termVector);
		doc.add(field);
		return field;
	}
	
	public static Item toItem(Document doc) {
		Item item = new Item();
		Map<String, String> fieldMap = new HashMap<String, String>();
		for (Fieldable field : doc.getFields()) {
			fieldMap.put(field.name(), field.stringValue());
		}
		item.setId(Long.parseLong(fieldMap.get("id")));
		item.setName(fieldMap.get("name"));
		item.setUrl(fieldMap.get("url"));
		item.setImgUrl(fieldMap.get("imgUrl"));
		item.setSiteName(fieldMap.get("siteName"));
		item.setDescription(fieldMap.get("description"));
		
		return item;
	}

}
